import { generateUUID } from 'src/common/utils/uuid';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateEnterpriseDto, ListEnterpriseDto, UpdateEnterpriseDto } from './dto/index';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { EnterpriseEntity } from './entities/enterprise.entity';

@Injectable()
export class EnterpriseService {
  constructor(
    @InjectRepository(EnterpriseEntity)
    private readonly enterpriseEntityRep: Repository<EnterpriseEntity>,
    // private readonly userService: UserService,
  ) {}
  async create(createEnterpriseDto: CreateEnterpriseDto) {
    const enterprise = await this.enterpriseEntityRep.findOne({
      where: {
        enterpriseName: createEnterpriseDto.enterpriseName,
        enterpriseAddress: createEnterpriseDto.enterpriseAddress,
      },
    });
    if (enterprise) throw new HttpException('企业已存在', HttpStatus.INTERNAL_SERVER_ERROR);
    const enterpriseId = generateUUID();
    const expireTime = new Date();
    expireTime.setTime(expireTime.getTime() + 30 * 24 * 60 * 60 * 1000);
    const result = this.enterpriseEntityRep.save({
      ...createEnterpriseDto,
      enterpriseId,
      expireTime,
    });
    return result;
  }

  async findAll(query: ListEnterpriseDto) {
    const entity = this.enterpriseEntityRep.createQueryBuilder('enterprise');
    const pageSize = query.pageSize || 10;
    const pageNum = query.pageNum || 1;

    if (query.enterpriseName) {
      entity.andWhere(`enterprise.enterpriseName LIKE "%${query.enterpriseName}%"`);
    }

    if (pageSize && pageNum) {
      entity.skip(pageSize * (pageNum - 1)).take(pageSize);
    }

    const [list, total] = await entity.getManyAndCount();
    const totalPage = Math.ceil(total / pageSize);
    return {
      list,
      total,
      totalPage,
      pageNum,
      pageSize,
    };
  }

  async findOne(id: string) {
    const entity = this.enterpriseEntityRep.createQueryBuilder('enterprise');
    entity.andWhere(`enterprise.enterpriseId = :enterpriseId`, { enterpriseId: id });
    return await entity.getOne();
  }

  update(id: number, updateEnterpriseDto: UpdateEnterpriseDto) {
    return `This action updates a #${id} enterprise`;
  }

  remove(id: number) {
    return `This action removes a #${id} enterprise`;
  }
}
